package com.hk.rabbitmq.service.business;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.hk.constants.MqConstants;
import com.hk.rabbitmq.domain.User;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class CommonBusiness {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final Gson GSON = new Gson();

    /**
     * 把MQ中的User写入到数据库中
     */
    public void mqSyncData() {
        User user = User.builder().id(1).username("张三").password("12345").build();
        String userJson = JSON.toJSONString(user);
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration("10000");

        Message message = new Message(GSON.toJson(user).getBytes(StandardCharsets.UTF_8), messageProperties);
        rabbitTemplate.convertAndSend(MqConstants.QUEUE_NAME, message);
    }



}
